<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model="name" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model="age" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click.prevent="addfn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(val, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ val.name }}</td>
          <td>{{ val.age }}</td>
          <td>{{ val.sex }}</td>
          <td>
            <button @click="delfn(index)">删除</button>
            <button @click="editfn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: "",
      sex: 0,
      age: "",
      flag: null,
      list: [
        {
          id: 1,
          name: "zs",
          age: 18,
          sex: "男",
        },
      ],
    };
  },
  methods: {
    addfn() {
      if (this.name == "" || this.age == "" || this.sex == "") {
        return;
      }
      if (this.flag != null) {
        // console.log(this.flag);
        this.list[this.flag].name = this.name;
        this.list[this.flag].age = this.age;
        this.list[this.flag].sex = this.sex;
        this.flag = null;
      } else {
        this.list.push({
          name: this.name,
          age: this.age,
          sex: this.sex,
        });
      }
      this.name = "";
      this.age = "";
      this.sex = "";
    },
    delfn(index) {
      this.list.splice(index, 1);
    },
    editfn(index) {
      this.flag = index;
      console.log(this.flag);
      this.name = this.list[index].name;
      this.sex = this.list[index].sex;
      this.age = this.list[index].age;
    },
  },
  // watch: {
  //   list: {
  //     handler(newArr) {
  //       localStorage.setItem("list", JSON.stringify(newArr));
  //     },
  //     deep: true,
  //     immediate: true,
  //   },
  // },
};
</script>
